package com.core;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class InitDate {

	private InitDate() {
	}

	private JdbcTemplate jdbcTemplate;
	public static JSONArray dictionnaryJsonArray = null;

	// 根据Id 获取一条字典记录
	public JSONObject getById(int id) {
		getDictionnary();
		int len = dictionnaryJsonArray.size();
		for (int i = 0; i < len; i++) {
			JSONObject json = (JSONObject) dictionnaryJsonArray.get(i);
			if (json.getInt("id") == id) {
				return json;
			}
		}
		return null;
	}

	/**
	 * 获取数据库字典
	 * 
	 * @return
	 */
	private void getDictionnary() {
		// 重数据库中获取字典数据
		if (dictionnaryJsonArray == null) {
			System.err.println("读取数据库字典-----------------");
			dictionnaryJsonArray = new JSONArray();
			List date = jdbcTemplate.queryForList("select * from m_dictionary");
			if (date != null && !date.isEmpty()) {
				int len = date.size();
				for (int i = 0; i < len; i++) {
					Map rowDate = (Map) date.get(i);
					Iterator it = rowDate.keySet().iterator();
					JSONObject jsonObject = new JSONObject();
					while (it.hasNext()) {
						String key = (String) it.next();
						jsonObject.put(key, rowDate.get(key));
					}
					dictionnaryJsonArray.add(jsonObject);
				}
			}
		}
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
